import { defineStore } from "pinia";
import router, { resetRouter } from "@/router/index.ts";
import {
    notFount,
    asyncRouters,
    rootRouter,
} from "@/router/routeMap.ts";
import { cloneDeep } from "lodash-es";
import { getMenusApi } from "@/api/loginApi/index.ts";
// 递归遍历路由，把有权限的路由遍历出来
const filterAsyncRoutes1 = (routes, idList) => {
    for (let i = 0, len = routes.length; i < len; i++) {
        const element = routes[i];
        if (idList.includes(element.name)) {
            if (element.children?.length) {
                // element.redirect = element.children[0].path;
                element.children = filterAsyncRoutes1(element.children, idList);
            }
        } else {
            routes.splice(i, 1);
            len = routes.length; // 删除后，需要重新计算长度
            if (i < len) {
                i--; // 删除后，数组后面的会往前移动一位，故需减一，否则会跳过下一位
            }
        }
    }
    return routes;
};
let stageMapAllRoutes: any[] = [] // 嵌套后的路由扁平化成一维数组
// 将routeMap中所有嵌套式的路由扁平化成一维数组，方便匹配
const handleFlatRoutes = () => {
    const stageRoutes = cloneDeep(asyncRouters);
    const newAsyncRoutes: any = [];
    const flatRoutes = (list: any[]) => {
        list.forEach((routeItem: any) => {
            const { path, name, meta, component } = routeItem
            newAsyncRoutes.push({ path, name, meta, component })
            if (routeItem.children?.length) {
                flatRoutes(routeItem.children)
            }
        })
    }
    flatRoutes(stageRoutes)
    stageMapAllRoutes = newAsyncRoutes
}
// 根据权限过滤出路由,并将其扁平化成一维数组（keepAlive时,根路径'/'的children必须是所有路由组成的一维数组）
const filterAsyncRoutes = (permissionArray: any[]) => {
    const stagePermission = cloneDeep(permissionArray);
    const flatList: any = [];
    const flatRoutes = (list: any[]) => {
        list.forEach((permissionItem: any) => {
            const { name, title: menuTile } = permissionItem;
            const target = stageMapAllRoutes.find((routeItem: any) => routeItem.name === name);
            if (target) {
                const { path, meta, component } = target
                const { title, hideMenu, ...restParams } = meta
                let childList = []
                if (hideMenu) {
                    childList = handleNestingRouter(name)
                }
                // 根据后端数据修改对应路由的信息，比如title,icon等可使用后端返回的
                const routeObj = {
                    path,
                    name,
                    meta: { title: menuTile ?? title, ...restParams, hideMenu },
                    component,
                    children: childList,
                }
                flatList.push(routeObj)
                permissionItem = {
                    ...permissionItem,
                    path,
                    meta: { title: menuTile, ...restParams },
                }
            }
            if (permissionItem.children?.length) {
                flatRoutes(permissionItem.children)
            }
        })
    }
    flatRoutes(stagePermission)
    return flatList
}
// 特殊处理（这种情况一般不会存在，某个页面中tab切换时路由相应改变，即大于二级的routerView嵌套）
const handleNestingRouter = (routeName: string) => {
    // 从扁平化的路由中找到它的子路由集合，作为children
    const list = stageMapAllRoutes.filter((item: any) => item.meta?.parentName === routeName)
    return list
}
// 根据权限将权限改造为菜单目录
const handleMapMenu = (permissionArray: any[]) => {
    const stagePermission = cloneDeep(permissionArray);
    const deepMenu = (list: any[], level: number) => {
        list.forEach((permissionItem: any) => {
            const { name } = permissionItem;
            const target = stageMapAllRoutes.find((routeItem: any) => routeItem.name === name);
            if (target) {
                const { path, meta, component } = target
                permissionItem.path = path
                permissionItem.meta = { ...meta, level }
                permissionItem.component = component
            }
            if (permissionItem.children?.length) {
                deepMenu(permissionItem.children, level + 1)
            }
        })
    }
    deepMenu(stagePermission, 1)
    return stagePermission
}
export const usePermissionStore = defineStore("permissionStore", {
    state: () => {
        return {
            permissionRoutes: [],
        };
    },
    getters: {},
    actions: {
        setRoutes(routeList: []) {
            this.permissionRoutes = routeList;
        },
        generateRoutes(permissionArray: []) {
            const _this = this;
            handleFlatRoutes()
            return new Promise((resolve) => {
                const flatList = filterAsyncRoutes(permissionArray);
                rootRouter.redirect = flatList[0].path;
                rootRouter.children = flatList; // 设置根路由的children，这是keep-alive的重点
                debugger
                const menuData = handleMapMenu(permissionArray)
                _this.setRoutes(menuData); // 把有权限的路由塞到pinia中
                resetRouter(); // 重置路由
                const routeList = [rootRouter];
                routeList.forEach((route: any) => {
                    router.addRoute(route); // 添加动态路由
                });
                router.addRoute('/', notFount); // 添加404
                resolve('success');
            });
        },
        getMenus(role: string) {
            const data = [
                { name: "home" },
                {
                    name: "user",
                    children: [
                        {
                            name: "userItemOne",
                            children: [
                                { name: "userItemOneChildOne" },
                                { name: "userItemOneChildTwo" },
                            ]
                        },
                        { name: "userItemTwo" }
                    ]
                },
                {
                    name: "apply",
                    children: [
                        { name: "applyItemOne" },
                        { name: "applyItemTwo" }
                    ]
                },
            ]
            return new Promise((resolve, reject) => {
                this.generateRoutes(data);
                resolve()
            })
            // return getMenusApi({ role })
            //     .then((res) => {
            //         if (res.code === 200) {
            //             debugger
            //             const data = res.data;
            //             const idList = data.map((item) => item.id);
            //             this.generateRoutes(idList);
            //             // this.setMenus(idList);
            //         }
            //     })
            //     .catch((err) => {
            //         return Promise.reject(err);
            //     });
        },
    },
    // persist: true, // true开启持久化，false关闭持久化
});
export default usePermissionStore;
